package org.linuxgears.BouncingBall;

import java.awt.*;
import java.awt.geom.Ellipse2D;

import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;

/**
 * Created by IntelliJ IDEA.
 * User: khilkeol
 * Date: 30 ���� 2010
 * Time: 12:45:26
 * To change this template use File | Settings | File Templates.
 */
public class BallRunnable implements Runnable, Comparable<BallRunnable> {

    public static final int TICKS = 1000;
    public static final int DELAY = 10;

    private Ball ball;
    
    private Thread thread;	// thread for this runnable

    private static int counter = 0;

   private int runnableId = counter++;

    public int getRunnableId() {
        return runnableId;
    }

    /**
     * Decoupling of runnable from model
     */
    private BallMover mover;

	public BallRunnable(Ball ball, BallMover mover) {
    	this.ball = ball;
        this.mover = mover;
    }

    @Override
    public void run() {
    	thread = Thread.currentThread();
    	System.out.println("Created thread " + thread.getName());

        while( ! thread.isInterrupted() ) {
            mover.move(ball);

            try {
                Thread.sleep(DELAY);	// or calculate something for SETI@HOME :)
            } catch (InterruptedException ex) {
            	System.out.println("Removing ball: " + ball.toString());
            	thread.interrupt();
            }
        }
    	System.out.println("Done thread " + thread.getName());
    }

    public Ball getBall() {
        return ball;
    }

    public BallMover getMover() {
		return mover;
	}

	public void setMover(BallMover mover) {
		this.mover = mover;
	}
	
    public void interrupt() {
    	System.out.println("Interrupting: " + thread.getName());
    	thread.interrupt();
    }
    
    @Override
    public int compareTo(BallRunnable that) {
        return this.getRunnableId() - that.getRunnableId();
    }
    
    @Override
    protected void finalize() throws Throwable {
    	// TODO Auto-generated method stub
    	super.finalize();
    	
    	System.out.println("Finilizing thread " + thread.getName());
    }
}
